<template>
  <div class="flex-alignc">
    <el-radio-group class="mr10" :model-value="type" @change="handleTypeChange">
      <el-radio-button v-for="(item, index) in typeList" :key="index" :label="item.label" :value="item.value" />
    </el-radio-group>
    <el-date-picker style="width: 200px" v-if="typeInfo.value != 4" class="power-date" :model-value="date"
      :type="typeInfo.type" :value-format="typeInfo.valueFormat" placeholder="请选择日期"
      :clearable="false" :disabled-date="disabledDate" @update:model-value="handleDateChange">
    </el-date-picker>
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance()
const props = defineProps({
  type: [String,Number], // 时间类型 1:日 2:月 3:年 4:总
  date: String, // 日期
  filter: String, // 时间类型过滤不显示
})
const emit = defineEmits(['update:type','update:date','change'])

// const typeList = ref([
//   { label: '日', value: 1, type: 'date', valueFormat: 'YYYY-MM-DD',dateFormat:'{y}-{m}-{d}' },
//   { label: '月', value: 2, type: 'month', valueFormat: 'YYYY-MM',dateFormat:'{y}-{m}' },
//   { label: '年', value: 3, type: 'year', valueFormat: 'YYYY',dateFormat:'{y}' },
//   { label: '总', value: 4, type: '', valueFormat: '',dateFormat:'' },
// ])
let list = [
  { label: '日', value: 1, type: 'date', valueFormat: 'YYYY-MM-DD',dateFormat:'{y}-{m}-{d}' },
  { label: '月', value: 2, type: 'month', valueFormat: 'YYYY-MM',dateFormat:'{y}-{m}' },
  { label: '年', value: 3, type: 'year', valueFormat: 'YYYY',dateFormat:'{y}' },
  { label: '总', value: 4, type: '', valueFormat: '',dateFormat:'' },
]
const typeList = computed(() => {
  return props.filter?list.filter(item => !props.filter.includes(item.label)):list
})

const typeInfo = computed(() => {
  let item = list.find(item => item.value == props.type)
  if(item) {
    if(props.type!=4) {
      emit('update:date',proxy.parseTime(new Date(), item.dateFormat))
    }else{
      emit('update:date','')
    }
  }
  return item?item:{}
})

// 日期类型改变
const handleTypeChange = async (e) => {
  try {
    await emit('update:type',e) // 同步操作,等待update:date更新完成,否则date数据还是上一次数据
    emit('change',{
      type: props.type,
      date: props.date,
    })
  }catch(err) {}
}

// 日期改变
const handleDateChange = (e) => {
  try {
    emit('update:date',e)
    emit('change',{
      type: props.type,
      date: props.date,
    })
  }catch(err) {}
}

const disabledDate = (time) => { // 只能选择当前日期之前的日期
  return Date.now() < time.getTime();
}
</script>

<style scoped lang="scss">
</style>
